if exists (select 1
          from sysobjects
          where  id = object_id('bd_fn_minToDateTime')
          and type in ('IF', 'FN', 'TF'))
   drop function bd_fn_minToDateTime
go


create function bd_fn_minToDateTime (@min INT,@date DATE)
RETURNS VARCHAR(50)
BEGIN
  IF (ISNULL(@min, 0) = 0)
    RETURN CONVERT(VARCHAR(10), @date, 120) + ' 00:00';

  DECLARE @result VARCHAR(50) = ''

  DECLARE @day INT = 0

  IF (ABS(@min) >= 1440)
  BEGIN
    SET @day = @min / 1440

    IF (@min < 0
      AND @day = 0)
      SET @day = -@day

    SET @date = DATEADD(DAY, @day, @date)
    SET @min = ABS(@min) % 1440
  END
  ELSE
  BEGIN
    IF (@min < 0)
      SET @date = DATEADD(DAY, -1, @date)
    SET @min = ABS(@min)
  END

  SET @result = CONVERT(VARCHAR(10), @date, 120) + ' ' + RIGHT('00' + CAST(@min / 60 AS VARCHAR(20)), 2) + ':' + RIGHT('00' + CAST(@min % 60 AS VARCHAR(20)), 2)

  RETURN @result
END
go
